<template>
  <transition appear name="animate__animated animate__bounce" enter-active-class="animate__lightSpeedInLeft"
    leave-active-class="animate__backOutDown">
    <li>
      <label>
        <input type="checkbox" :checked="todo.done" @click="handle_check_todo(todo.id)" />
        <span v-show="!todo.is_edit">{{ todo.title }}</span>
        <input v-show="todo.is_edit" @blur="blur_save(todo, $event)" type="text" :value="todo.title"
          ref="input_title" />
      </label>
      <button class="btn btn-danger" @click="del_element(todo.id)">删除</button>
      <button v-show="!todo.is_edit" class="btn btn-edit" @click="change_element(todo)">编辑</button>
    </li>
  </transition>

</template>

<script>
import 'animate.css'
export default {
  name: "Item",
  methods: {
    del_element(id) {
      if (confirm("确定删除？")) {
        this.$bus.$emit("del_todo", id)
      }
    },
    handle_check_todo(id) {
      this.$bus.$emit("check_todo", id)
    },
    change_element(todo) {
      if (!Object.hasOwnProperty(todo, "is_edit"))
        this.$set(todo, "is_edit", true)
      else
        this.is_edit = true
      // 下一次dom更新结束后，再执行回调函数中的代码 当改变数据后需要对dom操作
      this.$nextTick(function () {
        this.$refs.input_title.focus()
      })
    },
    blur_save(todo, e) {
      todo.is_edit = false
      let value = e.target.value.trim()
      if (!value) {
        alert("输入不能为空！")
        return
      }
      this.$bus.$emit("updata_todo", todo.id, value)
    }
  },
  props: {
    todo: {
      type: Object,
      required: true,
    }
  }
}
</script>

<style lang="less" scoped>
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover {
  background-color: #ddd;
}

li:hover button {
  display: block;
}
</style>